package purchaseStore

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
	"insighttracking/apps/purchase/auth"
	"insighttracking/apps/purchase/internal/svc"
	"insighttracking/apps/purchase/internal/types"
	"insighttracking/common/enum"
	"insighttracking/common/utils"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type CreatePurchaseStoreApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewCreatePurchaseStoreApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *CreatePurchaseStoreApiLogic {
	hostname, _ := os.Hostname()
	return &CreatePurchaseStoreApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *CreatePurchaseStoreApiLogic) CreatePurchaseStoreApi(req *types.CreatePurchaseStoreReq) (resp *types.CreatePurchaseStoreResp, err error) {
	resp = &types.CreatePurchaseStoreResp{}
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return
	}
	fmt.Println(k.MapToString(accountInfo), "用户信息")
	// 1.根据采购计划订单查询当前采购订单信息
	purchaseStoreDetailEntity, err := service.PurchaseStoreDetailService.GetPurchaseStoreByPurchaseStoreDetailIdApi(l.ctx, req.PurchaseStoreDetailId)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("传递的采购订单详情id错误")
		return
	}

	storeCount, _ := decimal.NewFromString(req.StoreCount)
	inCount := purchaseStoreDetailEntity.StoreCount.Add(storeCount)
	var inAmount decimal.Decimal
	if inCount.Compare(purchaseStoreDetailEntity.PurchaserCount) >= 0 {
		inAmount = purchaseStoreDetailEntity.PurchaserAmount
	} else {
		inAmount = inCount.Mul(purchaseStoreDetailEntity.PurchaserPrice)
	}

	tx := dao.Use(l.svcCtx.MysqlDb).Begin()
	// 修改入库重量和金额
	var batchNumber string
	if req.BatchNumber == "" {
		batchNumber = utils.StorageBatchNumber(l.svcCtx.RedisDb, time.Now(), purchaseStoreDetailEntity.SpuID, "RKPC")
	} else {
		batchNumber = req.BatchNumber
	}

	if err = service.PurchaseStoreDetailService.ModifyPurchaseStoreDetailByIdApi(
		l.ctx,
		tx,
		purchaseStoreDetailEntity.ID,
		inCount,
		inAmount,
		req.ShelfID,
		batchNumber,
		enum.PurchaseStoreEnum,
	); err != nil {
		if err = tx.Rollback(); err != nil {
			return
		}
		return
	}
	purchaseStoreEntity, err := service.PurchaseStoreService.GetPurchaseStoreByIdApi(l.ctx, accountInfo.EnterpriseId, purchaseStoreDetailEntity.PurchaseStoreID)
	if err != nil {
		if err = tx.Rollback(); err != nil {
			return
		}
		return
	}
	shelfEntity, err := service.ShelfService.GetInfoByIdApi(l.ctx, req.ShelfID)
	if err != nil {
		if err = tx.Rollback(); err != nil {
			return
		}
		return
	}
	// 修改主表的入库总重量
	if err = service.PurchaseStoreService.ModifyTotalCountByIdApi(l.ctx, tx, purchaseStoreDetailEntity.PurchaseStoreID, storeCount, accountInfo.PersonId); err != nil {
		if err = tx.Rollback(); err != nil {
			return
		}
		return
	}
	// 库存增加
	if err = service.SpuInventoryService.IncrInventoryApi(l.ctx, tx, accountInfo.EnterpriseId, shelfEntity.WarehouseID, purchaseStoreDetailEntity.SpuID, storeCount); err != nil {
		if err = tx.Rollback(); err != nil {
			return
		}
		return
	}
	// 货位库存增加
	if _, err = service.SpuShelfGridInventoryService.IncrGridInventoryApi(l.ctx, tx, accountInfo.EnterpriseId, req.ShelfID, purchaseStoreDetailEntity.SpuID, purchaseStoreEntity.SupplierID, req.ExpirationDate, batchNumber, storeCount); err != nil {
		if err = tx.Rollback(); err != nil {
			return
		}
		return
	}
	// 修改采购单详情的状态
	if err = service.PurchaseOrderDetailService.ModifyStatusByIdApi(l.ctx, tx, purchaseStoreDetailEntity.PurchaseOrdersDetailID, 10); err != nil {
		if err = tx.Rollback(); err != nil {
			return
		}
		return
	}
	// 库存记录
	if err = service.InventRecordService.CreateInventRecordApi(l.ctx, tx, &model.InventoryRecordEntity{
		EnterpriseID: accountInfo.EnterpriseId,                                 // 关联到enterprise表主键id
		SpuID:        purchaseStoreDetailEntity.SpuID,                          // 商品主键,关联到spu表主键id
		Types:        0,                                                        // 类型,0表示入库,1表示出库
		Source:       0,                                                        // 来源,0表示正常出入口,10表示盘点报损报溢,20表调拨
		WarehouseID:  shelfEntity.WarehouseID,                                  // 仓库id,关联到warehouse表主键id
		ChangeCount:  storeCount,                                               // 变动数量
		Price:        purchaseStoreDetailEntity.PurchaserPrice,                 // 单价
		Amount:       storeCount.Mul(purchaseStoreDetailEntity.PurchaserPrice), // 金额
		ShelfID:      req.ShelfID,                                              // 货位ID
		BatchNumber:  batchNumber,                                              // 批次号
	}); err != nil {
		if err = tx.Rollback(); err != nil {
			return
		}
		return
	}
	// 修改称重的状态
	if err = service.SpuStoreWeighRecordService.ModifyStatusBySpuIdApi(l.ctx, tx, accountInfo.EnterpriseId, purchaseStoreDetailEntity.SpuID); err != nil {
		if err = tx.Rollback(); err != nil {
			return
		}
		return
	}
	if err = tx.Commit(); err != nil {
		return
	}
	resp.BatchNumber = batchNumber
	// 后面进行的数据操作
	go ModifyStatus(accountInfo.EnterpriseId, purchaseStoreEntity.PurchaseOrdersID, purchaseStoreEntity.ID)
	return
}

func ModifyStatus(enterpriseId, purchaseOrderId, purchaseStoreId int64) {
	fmt.Println("------------------开始修改状态------------------")
	// 判断是否要修改采购单的状态
	purchaseOrdersDetailEntities, err := service.PurchaseOrderDetailService.GetByPurchaseOrderIdApi(context.Background(), []int64{purchaseOrderId})
	if err == nil && len(purchaseOrdersDetailEntities) > 0 {
		logx.Infof("修改采购入库单状态")
		isComplete := k.Every(purchaseOrdersDetailEntities, func(item *model.PurchaseOrdersDetailEntity, index int) bool {
			return item.StoreStatus != 0
		})
		if isComplete {
			if err := service.PurchaseOrderService.ModifyStatusByIdApi(context.Background(), purchaseOrderId, enum.PurchaseOrderCompletedEnum); err != nil {
				logx.Errorf("修改订单状态失败,需要人工去维护数据:【%d】", purchaseOrderId)
			}

			// TODO 生成出货报表
			purchaseOrder, _ := service.PurchaseOrderService.GetPurchaseOrderByIdApi(context.Background(), enterpriseId, purchaseOrderId)
			entity := &model.FinancialStatisticsEntity{
				ID:          "GYSJK" + uuid.New().String(),
				Type:        2,
				RelatedType: 2,
				RelationID:  purchaseOrderId,
				SupplierID:  purchaseOrder.SupplierID,
				Amount:      purchaseOrder.PurchaserTotalAmount,
			}
			_ = service.FinancialStatistics.CreateApi(context.Background(), entity)
		} else {
			if err := service.PurchaseOrderService.ModifyStatusByIdApi(context.Background(), purchaseOrderId, enum.PurchaseOrderPartCompletedEnum); err != nil {
				logx.Errorf("修改订单状态失败,需要人工去维护数据:【%d】", purchaseOrderId)
			}
		}
	}
	// 修改主表的状态
	logx.Infof("----修改主表状态----")
	storeDetailEntities, err := service.PurchaseStoreDetailService.GetPurchaseStoreByParentIdApi(context.Background(), purchaseStoreId)
	if err == nil && len(storeDetailEntities) > 0 {
		isComplete := k.Every(storeDetailEntities, func(item *model.PurchaseStoreDetailEntity, index int) bool {
			return item.StoreStatus == enum.PurchaseStoreEnum
		})
		if isComplete {
			if err := service.PurchaseStoreService.ModifyStatusByIdApi(context.Background(), purchaseStoreId, enum.PurchaseStoreEnum); err != nil {
				logx.Errorf("修改采购入库单状态失败：【%d】", purchaseStoreId)
			}
		} else {
			if err := service.PurchaseStoreService.ModifyStatusByIdApi(context.Background(), purchaseStoreId, enum.PurchaseStorePartEnum); err != nil {
				logx.Errorf("修改采购入库单状态失败：【%d】", purchaseStoreId)
			}
		}
	}
	fmt.Println(purchaseOrdersDetailEntities, "修改采购单状态2")

	//if purchasePlanId > 0 { // 从采购计划过来的
	//	// 根据采购计划查找订单
	//	planEntities, err := service.PurchasePlanService.GetByIdListApi(context.Background(), []int64{purchasePlanId}, []int64{})
	//	if err == nil && len(planEntities) > 0 {
	//		// 找到订单详情
	//		purchasePlanList := k.Filter(planEntities, func(item *model.PurchasePlanEntity, index int) bool {
	//			return item.OrdersDetailID > 0
	//		})
	//		if len(purchasePlanList) > 0 {
	//			ordersDetailIDList := k.Map(purchasePlanList, func(item *model.PurchasePlanEntity, index int) int64 {
	//				return item.OrdersDetailID
	//			})
	//			if err = service.OrdersDetailService.ModifyStatusByIdListApi(context.Background(), ordersDetailIDList, 40); err != nil {
	//				logx.Errorf("修改订单详情状态失败:[%v]", ordersDetailIDList)
	//			}
	//			fmt.Println("修改订单详情状态3")
	//			// 找到订单
	//			ordersDetailEntities, err := service.OrdersDetailService.GetByIdListApi(context.Background(), ordersDetailIDList)
	//			if err == nil && len(ordersDetailEntities) > 0 {
	//				orderIdList := k.Map(ordersDetailEntities, func(item *model.OrdersDetailEntity, index int) int64 {
	//					return item.OrdersID
	//				})
	//				for _, orderId := range orderIdList {
	//					detailEntities, err := service.OrdersDetailService.GetByOrderIdListApi(context.Background(), []int64{orderId})
	//					if err == nil && len(detailEntities) > 0 {
	//						if k.Every(detailEntities, func(item *model.OrdersDetailEntity, index int) bool {
	//							return item.Status == 40
	//						}) {
	//							if err = service.OrdersService.ModifyStatusByIdApi(context.Background(),&dao.QueryTx{}, []int64{orderId}, 4); err != nil {
	//								logx.Errorf("修改订单状态失败:[%v]", orderId)
	//							}
	//						}
	//					}
	//				}
	//			}
	//			fmt.Println("修改订单状态4--")
	//		}
	//
	//	}
	//}

}
